package com.serice;

import com.alibaba.fastjson.JSONArray;
import com.dao.CustomModelDao;
import com.dao.CustomModelInfoDao;
import com.entity.CustomModel;
import com.entity.CustomModelInfo;
import com.enums.YesNoEnum;
import com.form.*;
import com.mapper.MryeMapper;
import com.util.BeanConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by SkinApe on 2021/8/6.
 */
@Service
public class MreService {


    @Autowired
    private MryeMapper mryeMapper;

    @Autowired
    private CustomModelInfoDao customModelInfoDao;
    @Autowired
    private CustomModelDao customModelDao;

    /**
     * 新增/修改
     *
     * @param params
     */
    @Transactional
    public int saveAndFlush(Map<String, Object> params) {
        int result=0;
        //模块名
        String modelName = ValueUtil.toStr(params.get("modelName"));
        //数据集
        List<Map<String, Object>> dataList = (List<Map<String, Object>>) params.get("data");
        StringBuffer sql = new StringBuffer("SELECT * FROM a_custom_model WHERE model_name=#{code}");

        params.put("sql", sql);
        params.put("code", modelName);
        CustomModelForm customModelForm = BeanConvertUtils.sourceToTarget(BeanConvertUtils.lineToHumpMap(mryeMapper.search(params)), CustomModelForm.class);

        if (customModelForm != null) {
            modelName = customModelForm.getTableName();
        }
        params.put("code", modelName);


        sql = new StringBuffer("SELECT * FROM a_custom_info WHERE table_name=#{code} ORDER BY id");
        params.put("sql", sql);
        List<CustomTableLineForm> customModelInfoFormList = BeanConvertUtils.sourceListToTargetList(BeanConvertUtils.lineToHumpMapList(mryeMapper.searchList(params)), CustomTableLineForm.class);
        if (customModelInfoFormList.size() == 0) {
            throw new RuntimeException("模块/表 不存在！");
        }


        //批量新增值
        List<Map<String, Object>> insertValues = new ArrayList<Map<String, Object>>();
        //批量新增语句
        StringBuffer insertSql = new StringBuffer("");
        //批量新增值语句
        StringBuffer insertValueSql = new StringBuffer("");

        //批量修改语句
        StringBuffer updateSql = null;
        //批量修改值语句
        List<Map<String, Object>> updateValueSqlMap = new ArrayList<>();

        for (Map<String, Object> data : dataList) {

            updateSql = new StringBuffer("");


            Map<String, Object> insertValue = new HashMap<>();
            Map<String, Object> updateValue = new HashMap<>();


            //有id修改 无id新增
            boolean isId = data.containsKey("id");

            if (!isId || data.get("id").equals(0)) {
                insertSql = new StringBuffer("");
                insertValueSql = new StringBuffer("");
            }

            for (String fieldAlias : data.keySet()) {

                for (CustomTableLineForm customTableLineForm : customModelInfoFormList) {

                    if (customTableLineForm.getFieldAlias().equals(fieldAlias)) {
                        //在模块里存在字段
                        if (!isId || data.get("id").equals(0)) {
                            //新增
                            insertSql.append(customTableLineForm.getField() + ",");
                            insertValueSql.append("#{item." + fieldAlias + "},");

                            insertValue.put(fieldAlias, data.get(fieldAlias));

                        } else {

                            updateValue.put("id", data.get("id"));

                            //修改
                            updateSql.append(customTableLineForm.getField() + "=#{item.values." + fieldAlias + "},");

                            updateValue.put(fieldAlias, data.get(fieldAlias));

                        }

                    }

                }


            }

            if (insertValue.size() > 0) {
                insertValues.add(insertValue);
            }

            if (updateSql.length() > 0) {
                Map<String, Object> updateValueSql = new HashMap<>();
                updateValueSql.put("sql", "UPDATE " + modelName + " SET " + updateSql.substring(0, updateSql.length() - 1) + " WHERE id=#{item.values.id}");
                updateValueSql.put("values", updateValue);
                updateValueSqlMap.add(updateValueSql);
            }
        }

        if (insertValueSql.length() > 0) {
            insertSql = new StringBuffer(insertSql.insert(0, "INSERT INTO " + modelName + "( ").substring(0, insertSql.length() - 1)).append(") VALUES ");
        }

        System.out.println(insertSql);
        System.out.println(updateValueSqlMap);

        if (insertSql.length() > 0) {
            params.put("sql", insertSql);
            params.put("sqlValue", "( " + insertValueSql.substring(0, insertValueSql.length() - 1) + ")");
            result=mryeMapper.saveBatch(params, insertValues);
        }
        if (updateValueSqlMap.size() > 0) {
            result=result+mryeMapper.updateBatch(updateValueSqlMap);
        }

        return result;
    }


    /**
     * 删除
     * @param params
     */
    @Transactional
    public int delete(Map<String, Object> params){
        int result=0;

        //模块名
        String modelName = ValueUtil.toStr(params.get("modelName"));
        //数据集
        List<Map<String, Object>> dataList = (List<Map<String, Object>>) params.get("data");
        StringBuffer sql = new StringBuffer("SELECT * FROM a_custom_model WHERE model_name=#{code}");

        params.put("sql", sql);
        params.put("code", modelName);
        CustomModelForm customModelForm = BeanConvertUtils.sourceToTarget(BeanConvertUtils.lineToHumpMap(mryeMapper.search(params)), CustomModelForm.class);

        if (customModelForm != null) {
            modelName = customModelForm.getTableName();
        }
        params.put("code", modelName);


        sql = new StringBuffer("SELECT * FROM a_custom_info WHERE table_name=#{code} ORDER BY id");
        params.put("sql", sql);
        List<CustomTableLineForm> customModelInfoFormList = BeanConvertUtils.sourceListToTargetList(BeanConvertUtils.lineToHumpMapList(mryeMapper.searchList(params)), CustomTableLineForm.class);
        if (customModelInfoFormList.size() == 0) {
            throw new RuntimeException("模块/表 不存在！");
        }


        StringBuffer deleteSql=new StringBuffer("");

        for (Map<String,Object>data:dataList){
            deleteSql.append("DELETE FROM " + modelName + " WHERE ");
            for (String fieldAlias : data.keySet()) {

                for (CustomTableLineForm customTableLineForm : customModelInfoFormList) {

                    if (customTableLineForm.getFieldAlias().equals(fieldAlias)) {
                        deleteSql.append(customTableLineForm.getField()+"=#{"+fieldAlias+"} AND ");
                        params.put(fieldAlias, data.get(fieldAlias));
                    }

                }
            }
            deleteSql=new StringBuffer(deleteSql.substring(0, deleteSql.length() - 4)+";");
        }
        if (deleteSql.length()>0) {

            params.put("sql", deleteSql);
            result=mryeMapper.delete(params);
        }
        System.out.println(deleteSql);


        return result;

    }

    /**
     * 创建模块
     * @param dataBody
     */
    @Transactional
    public void createModel(Map<String, Object> dataBody){
        StringBuffer sql=new StringBuffer("");
        Map<String, Object> params=new HashMap<>();
        //模块主表
        CustomModelForm customModelForm= BeanConvertUtils.sourceMapToTarget(dataBody,CustomModelForm.class);
        //模块子表
        List<CustomModelInfoForm> customModelInfoFormList=BeanConvertUtils.sourceListToTargetList((List<Map<String, Object>>) dataBody.get("modelInfo"),CustomModelInfoForm.class);
        String tableNameAlias=ValueUtil.toStr(customModelForm.getTableNameAlias());
        if (tableNameAlias.equals("")){
            //新模块 获取最大别名
            sql=new StringBuffer("SELECT MAX(id)+1 AS max FROM a_custom_model");
            params.put("sql",sql);
            Map<String, Object> maxId = mryeMapper.search(params);
            tableNameAlias="t"+maxId.get("max");
        }
        customModelForm.setTableNameAlias(tableNameAlias);

        //处理子表的别名
        for (CustomModelInfoForm customModelInfoForm:customModelInfoFormList){

            //获取最大关联表别名
            sql=new StringBuffer("SELECT count(1)+1 AS max FROM a_custom_model_info WHERE model_name=#{modelName} AND join_table<>''");
            params.put("sql",sql);
            params.put("modelName",customModelForm.getModelName());
            Map<String, Object> maxId = mryeMapper.search(params);
            int joinTableId=ValueUtil.toInt(maxId.get("max"));
            int joinTableSonId=1;

            customModelInfoForm.setModelName(customModelForm.getModelName());

            if (customModelInfoForm.getTableName().equals("")){
                customModelInfoForm.setTableName(customModelForm.getTableName());
                customModelInfoForm.setTableNameAlias(customModelForm.getTableNameAlias());
            }



            List<CustomModelInfoJoinTableForm> joinList=BeanConvertUtils.sourceListToTargetList(customModelInfoForm.getJoinTableList(),CustomModelInfoJoinTableForm.class);
            Collections.sort(joinList, new Comparator<CustomModelInfoJoinTableForm>() {
                @Override
                public int compare(CustomModelInfoJoinTableForm o1, CustomModelInfoJoinTableForm o2) {
                    Long name1 = o1.getId();
                    Long name2 = o2.getId();
                    return name1.compareTo(name2);
                }
            });
            for (int i=0;i<joinList.size();i++){
                CustomModelInfoJoinTableForm join=joinList.get(i);
                if (i==0){
                    //第一次
                    join.setTableAlias(customModelForm.getTableNameAlias());
                    join.setJoinTableAlias(join.getTableAlias()+joinTableId);
                }else {
                    CustomModelInfoJoinTableForm preJoin=joinList.get(i-1);

                    join.setTableAlias(preJoin.getJoinTableAlias());
                    join.setJoinTableAlias(customModelForm.getTableNameAlias()+joinTableId+joinTableSonId);
                    joinTableSonId++;
                }


            }
            customModelInfoForm.setJoinTable(JSONArray.toJSONString(joinList));

        }
        List<CustomModelInfo> customModelInfos=BeanConvertUtils.sourceListToTargetList(customModelInfoFormList,CustomModelInfo.class);
        customModelInfoDao.saveAll(customModelInfos);

        CustomModel customModel=BeanConvertUtils.sourceToTarget(customModelForm,CustomModel.class);
        customModelDao.saveAndFlush(customModel);




    }

    /**
     * 获取模块信息
     *
     * @param
     * @return
     */
    public Map<String, Object> viewModel(Map<String, Object> view) {

        Map<String, Object> result = new HashMap<>();

        Map<String, Object> params = new HashMap();


        //子模块层级存储
        Map<String, Object> sonModelSqlMap = new LinkedHashMap<>();

        //枚举名
        Map<String, String> enumerationMap = new HashMap<>();
        //枚举数据
        Map<String, Object> enumerationList = new HashMap<>();
        //字段属性存储
        Map<String, Object> fieldAttribute = new HashMap<>();

        String modelName = ValueUtil.toStr(view.get("modelName"));
        String sql = "SELECT * FROM a_custom_model WHERE model_name=#{code}";
        params.put("sql", sql);
        params.put("code", modelName);
        CustomModelForm customModelForm = BeanConvertUtils.sourceToTarget(customModelDao.findByModelName(modelName), CustomModelForm.class);
        if (customModelForm != null) {

            //拼接子模块
            Map<String, String> sonSelect = splicingSon(new HashMap<>(), 2, modelName, enumerationMap, fieldAttribute, sonModelSqlMap);
            String selectSql = sonSelect.get("selectSql");
            String joinSql = sonSelect.get("joinSql");

            selectSql = selectSql.substring(0, selectSql.length() - 1);
            sql = "SELECT ";
            sql = sql + selectSql + " FROM " + customModelForm.getTableName() + " " + customModelForm.getTableNameAlias() + joinSql;


            for (String key : enumerationMap.keySet()) {
                //把枚举数据封装进去
                params.put("sql", "SELECT enumeration_key,enumeration_value,enumeration_value FROM a_custom_enumeration_info WHERE enumeration_key=#{code}");
                params.put("code", enumerationMap.get(key));
                List<Map<String, Object>> mapList = BeanConvertUtils.lineToHumpMapList(mryeMapper.searchList(params));
                enumerationList.put(enumerationMap.get(key), mapList);
            }


            System.out.println("功能SQL: " + sql);
            params.put("sql", sql);
            params.put("code", modelName);
            params.put("view", view);
            List<Map<String, Object>> mapList = mryeMapper.searchAopList(params);

            //组装子模块数据集
            splicingData(mapList, sonModelSqlMap, sonModelSqlMap.size());


            List<Map<String, String>> groupList = (List<Map<String, String>>) params.get("groupList");
            if (groupList != null && groupList.size() > 0) {
                Map<String, List<Map<String, Object>>> collect = mapList.stream().collect(Collectors.groupingBy(item -> {
                    String condition = "";
                    for (Map<String, String> group : groupList) {

                        Map<String, Object> keyMap = parseMapForFilter(item, group.get("field"));
                        if (keyMap.size() > 0) {
                            condition = condition + item.get(keyMap.keySet().iterator().next()) + "——>";
                        }
                    }

                    return condition;
                }));
                result.put("data", collect);
            } else {

                result.put("data", mapList);
            }
            result.put("page", params.get("page"));
            result.put("size", params.get("size"));
            result.put("total", params.get("count"));
            result.put("fieldAttribute", fieldAttribute);
            result.put("enumerationList", enumerationList);

            return result;
        }
        return null;
    }

    /**
     * 创建表或者列
     *
     * @param customTableForm
     * @return
     */
    public void createTable(CustomTableForm customTableForm) {
        StringBuffer sql = new StringBuffer();
        List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
        Map<String, Object> params = new HashMap();

        String table = customTableForm.getTable();
        List<CustomTableLineForm> customTableLines = customTableForm.getLine();

        //查询表是否存在 如果存在就是新增列
        sql.append("SELECT COUNT(*) FROM pg_class WHERE relname = #{table};");
        params.put("sql", sql.toString());
        params.put("table", table);
        Map<String, Object> sqlMap = mryeMapper.search(params);
        int isCun = ValueUtil.toInt(sqlMap.get("count"));


        sql = new StringBuffer();
        //首先创建自增长
        for (CustomTableLineForm customTableLine : customTableLines) {
            if (customTableLine.getIsPrimary().equals(YesNoEnum.YES.getCode())) {
                sql.append(" CREATE SEQUENCE IF NOT EXISTS " + table + "_" + customTableLine.getField() + "_seq START 1; ");
            }
        }

        //不存在表添加表和字段
        if (isCun == 0) {
            sql.append(" CREATE TABLE IF NOT EXISTS " + table + " ( ");
        }


        for (int i = 0; i < customTableLines.size(); i++) {
            if (isCun == 1) {
                sql.append("ALTER  TABLE  " + table + "  ADD COLUMN  ");
            }
            CustomTableLineForm customTableLine = customTableLines.get(i);

            String field = customTableLine.getField();
            String fieldAlias = customTableLine.getFieldAlias();
            String type = customTableLine.getType();
            String isPrimary = customTableLine.getIsPrimary();
            String isNull = customTableLine.getIsNull();
            String isGrowth = customTableLine.getIsGrowth();
            String defaultValue = customTableLine.getDefaultValue();
            String remark = customTableLine.getRemark();
            sql.append(field + " " + type);
            if (isPrimary.equals(YesNoEnum.YES.getCode())) {
                sql.append(" primary key ");
            }
            if (isNull.equals(YesNoEnum.No.getCode())) {
                sql.append(" NOT NULL ");
            }

            if (isGrowth.equals(YesNoEnum.YES.getCode())) {
                sql.append(" DEFAULT nextval('" + table + "_" + field + "_seq'::regclass)");
            } else {
                if (!ValueUtil.toStr(defaultValue).equals("")) {
                    if (type.contains("timestamp")) {
                        sql.append(" DEFAULT CURRENT_TIMESTAMP ");
                    } else {
                        sql.append(" DEFAULT '" + defaultValue + "' ");
                    }
                }
            }
            if (i < customTableLines.size() - 1 && isCun == 0) {
                sql.append(",");
            }
            if (isCun == 1) {
                sql.append(";");
            }

            //新增记录

            Map<String, Object> value = new HashMap<String, Object>();
            value.put("table_name", table);
            value.put("field", field);
            value.put("field_alias", fieldAlias);
            value.put("type", type);
            value.put("remark", remark);
            value.put("is_custom", YesNoEnum.YES.getCode());

            values.add(value);
        }
        if (isCun == 0) {
            sql.append(" );");
        }
        //添加备注
        for (CustomTableLineForm customTableLine : customTableLines) {
            String name = customTableLine.getField();
            String remark = customTableLine.getRemark();
            if (!ValueUtil.toStr(remark).equals("")) {
                sql.append(" COMMENT ON COLUMN " + table + "." + name + " IS '" + remark + "'; ");
            }

        }


        params.put("sql", sql.toString());

        mryeMapper.update(params);


        sql = new StringBuffer("SELECT count(1) FROM a_custom WHERE table_name=#{table}");
        params.put("sql", sql.toString());
        sqlMap = mryeMapper.search(params);
        isCun = ValueUtil.toInt(sqlMap.get("count"));
        if (isCun==0){
            sql = new StringBuffer("INSERT INTO a_custom (table_name, table_name_alias, is_custom) VALUES ( #{table}, #{tableName}, 'Y');");
            params.put("sql", sql.toString());
            params.put("tableName", customTableForm.getTableName());
            mryeMapper.saveSap(params);
        }


        sql = new StringBuffer("INSERT INTO a_custom_info ( table_name, field, field_alias, type, remark, is_custom ) VALUES");
        params.put("sql", sql.toString());
        params.put("sqlValue", "(#{item.table_name},#{item.field},#{item.field_alias},#{item.type},#{item.remark},#{item.is_custom})");
        mryeMapper.saveBatch(params, values);
    }


    /**
     * 拼接查询语句
     *
     * @param selectSql
     * @param joinSql
     * @param customModelInfoForm
     * @return
     */
    public Map<String, String> splicingSelect(String selectSql, String joinSql, CustomModelInfoForm customModelInfoForm) {
        Map<String, String> result = new HashMap<>();
        //是否存在枚举值
        if (!ValueUtil.toStr(customModelInfoForm.getEnumerationKey()).equals("")) {


            selectSql = selectSql + " eninfo" + customModelInfoForm.getId() + ".enumeration_name AS \"" + customModelInfoForm.getShowName() + "|" + customModelInfoForm.getTableFieldAlias() + "|" + customModelInfoForm.getShowPosition() + "\",";
            joinSql = joinSql + " LEFT JOIN a_custom_enumeration_info eninfo" + customModelInfoForm.getId() + " ON '" + customModelInfoForm.getEnumerationKey() + "' = eninfo" + customModelInfoForm.getId() + ".enumeration_key AND CAST (" + customModelInfoForm.getTableNameAlias() + "." + customModelInfoForm.getTableField() + " AS VARCHAR) = eninfo" + customModelInfoForm.getId() + ".enumeration_value ";

        } else {
            if (customModelInfoForm.getIsDatabase().equals("Y")) {
                if (!ValueUtil.toStr(customModelInfoForm.getJoinType()).equals("")) {
                    //if (customModelInfoForm.getIsMultiTable().equals("Y")){
                    List<Map> joinMapList = JSONArray.parseArray(customModelInfoForm.getJoinTable(), Map.class);

                    List<CustomModelInfoJoinTableForm> joinList=BeanConvertUtils.sourceListToTargetList(joinMapList,CustomModelInfoJoinTableForm.class);

                    //多连表查询的
                    Collections.sort(joinList, new Comparator<CustomModelInfoJoinTableForm>() {
                        public int compare(CustomModelInfoJoinTableForm o1, CustomModelInfoJoinTableForm o2) {
                            Long name1 = o1.getId();
                            Long name2 = o2.getId();
                            return name1.compareTo(name2);
                        }
                    });

                    String joinTableAlias="";
                    //遍历连接表
                    for (CustomModelInfoJoinTableForm join : joinList) {
                        String table = join.getTable();
                        String tableAlias = join.getTableAlias();
                        String[] fieldList = join.getField().split("\\|");
                        String[] fieldAliasList = join.getFieldAlias().split("\\|");

                        String joinTable = join.getJoinTable();
                        joinTableAlias = join.getJoinTableAlias();
                        String[] joinFieldList = join.getJoinField().split("\\|");
                        String[] joinFieldAliasList = join.getJoinFieldAlias().split("\\|");

                        joinSql = joinSql + customModelInfoForm.getJoinType() + " " + joinTable + " " + joinTableAlias + " ON ";

                        for (int i = 0; i < fieldList.length; i++) {
                            String field = fieldList[i];
                            String joinField = joinFieldList[i];
                            joinSql = joinSql + joinTableAlias + "." + joinField + "=" + tableAlias + "." + field + " AND ";
                        }

                        joinSql = joinSql.substring(0, joinSql.length() - 4);


                    }
//                }else {
//                    //单连表查询的
//                    joinSql = joinSql + customModelInfoForm.getJoinType() + " " + customModelInfoForm.getJoinTable() + " " + customModelInfoForm.getJoinTableAlias() + " ON " + customModelInfoForm.getTableNameAlias() + "." + customModelInfoForm.getJoinTableFieldSource() + "=" + customModelInfoForm.getJoinTableAlias() + "." + customModelInfoForm.getJoinTableFieldTarget() + " ";
//                }
                    selectSql = selectSql + joinTableAlias;
                } else {
                    selectSql = selectSql + customModelInfoForm.getTableNameAlias();
                }
                selectSql = selectSql + "." + customModelInfoForm.getTableField();
            } else {

                selectSql = selectSql + " '只是为了展示' ";
            }
            selectSql = selectSql + " AS \"" + customModelInfoForm.getShowName() + "|" + customModelInfoForm.getTableFieldAlias() + "|" + customModelInfoForm.getShowPosition() + "\",";
        }

        result.put("selectSql", selectSql);
        result.put("joinSql", joinSql);
        return result;
    }


    /**
     * 拼接子模块
     *
     * @param modelNames     不允许嵌套循环   默认！
     * @param forCount       为了限制无限嵌套循环 循环次数  (如 主表-子表-主表-子表) 一般情况不会出现
     * @param modelName
     * @param enumerationMap
     * @param fieldAttribute
     * @param sonModelSqlMap
     * @return
     */
    public Map<String, String> splicingSon(Map<String, String> modelNames, int forCount, String modelName, Map<String, String> enumerationMap, Map<String, Object> fieldAttribute, Map<String, Object> sonModelSqlMap) {
        Map<String, String> result = new HashMap();
        String selectSql = " ";
        String joinSql = " ";
        Map<String, Object> params = new HashMap();
        String sql = "SELECT * FROM a_custom_model_info WHERE model_name=#{code} ORDER BY sort";
        params.put("code", modelName);
        params.put("sql", sql);
        List<CustomModelInfoForm> customModelInfoFormList = BeanConvertUtils.sourceListToTargetList(customModelInfoDao.findByModelNameOrderBySort(modelName), CustomModelInfoForm.class);
        sql = "SELECT ";
        for (CustomModelInfoForm customModelInfoForm : customModelInfoFormList) {


            String currentModelName = ValueUtil.toStr(customModelInfoForm.getSonModel());

            //没有子模块关联数据 或者 没有关联数据(也就是 选择其它表的数据)
            if (currentModelName.equals("") || !currentModelName.equals("") && ValueUtil.toStr(customModelInfoForm.getJoinTable()).equals("")) {
                Map<String, String> data = splicingSelect(selectSql, joinSql, customModelInfoForm);
                selectSql = data.get("selectSql");
                joinSql = data.get("joinSql");
                if (!ValueUtil.toStr(customModelInfoForm.getEnumerationKey()).equals("")) {
                    enumerationMap.put(customModelInfoForm.getTableFieldAlias(), customModelInfoForm.getEnumerationKey());
                }
                addFieldAttribute(fieldAttribute, customModelInfoForm);
            } else {
                //允许嵌套/不允许嵌套 &&!modelNames.containsKey(currentModelName)
                if (!currentModelName.equals(modelName) && forCount > 0) {
                    forCount--;
                    modelName = currentModelName;
                    //有子模块
                    Map<String, String> sonSelect = splicingSon(modelNames, forCount, modelName, enumerationMap, fieldAttribute, sonModelSqlMap);
                    sonModelSqlMap.put(ValueUtil.toStr(sonModelSqlMap.size() + 1), splicingSonData(sonSelect.get("selectSql"), sonSelect.get("joinSql"), sql, customModelInfoForm));
                    addFieldAttribute(fieldAttribute, customModelInfoForm);
                }

            }
            modelNames.put(customModelInfoForm.getModelName(), "Y");

        }
        result.put("selectSql", selectSql);
        result.put("joinSql", joinSql);
        return result;
    }


    /**
     * 拼接子模块的数据集
     *
     * @param selectSonSql
     * @param joinSonSql
     * @param sonQql
     * @param customModelInfoForm
     * @return
     */
    public List<Map<String, Object>> splicingSonData(String selectSonSql, String joinSonSql, String sonQql, CustomModelInfoForm customModelInfoForm) {
        //子模块
        List<Map<String, Object>> sonSqlMapList = new ArrayList();
        selectSonSql = selectSonSql.substring(0, selectSonSql.length() - 1);

        sonQql = sonQql + selectSonSql + " FROM " + customModelInfoForm.getTableName() + " " + customModelInfoForm.getTableNameAlias() + joinSonSql + " WHERE 1=1 ";


        List codeList = new ArrayList();

        List<Map> joinMapList = JSONArray.parseArray(customModelInfoForm.getJoinTable(), Map.class);

        List<CustomModelInfoJoinTableForm> joinList=BeanConvertUtils.sourceListToTargetList(joinMapList,CustomModelInfoJoinTableForm.class);

        //多连表查询的
        Collections.sort(joinList, new Comparator<CustomModelInfoJoinTableForm>() {
            public int compare(CustomModelInfoJoinTableForm o1, CustomModelInfoJoinTableForm o2) {
                Long name1 = o1.getId();
                Long name2 = o2.getId();
                return name1.compareTo(name2);
            }
        });

        String joinTableAlias="";
        //遍历连接表
        for (CustomModelInfoJoinTableForm join : joinList) {
            String table = join.getTable();
            String tableAlias = join.getTableAlias();
            String[] fieldList = join.getField().split("\\|");
            String[] fieldAliasList = join.getFieldAlias().split("\\|");

            String joinTable = join.getJoinTable();
            joinTableAlias = join.getJoinTableAlias();
            String[] joinFieldList = join.getJoinField().split("\\|");
            String[] joinFieldAliasList = join.getJoinFieldAlias().split("\\|");


            for (int i = 0; i < fieldList.length; i++) {
                String field = fieldList[i];
                String joinField = joinFieldList[i];
                String joinFieldAlias = joinFieldAliasList[i];
                sonQql = sonQql + " AND " + customModelInfoForm.getTableNameAlias() + "." + field + "=#{" + joinFieldAlias + "} ";

                codeList.add(joinFieldAlias);
            }


        }


        System.out.println("功能子模块Sql: " + sonQql);
        Map<String, Object> sonSqlMap = new HashMap<>();
        sonSqlMap.put("codeList", codeList);
        sonSqlMap.put("sonQql", sonQql);
        sonSqlMap.put("list", customModelInfoForm.getShowName() + "|" + customModelInfoForm.getTableFieldAlias() + "|" + customModelInfoForm.getShowPosition());
        sonSqlMapList.add(sonSqlMap);

        return sonSqlMapList;
    }

    /**
     * 组装子模块数据集
     */
    public void splicingData(List<Map<String, Object>> mapList, Map<String, Object> sonModelSqlMap, int iteratorKey) {
        Map<String, Object> params = new HashMap();

        for (Map<String, Object> map : mapList) {
            if (map.size() > 0 && iteratorKey > 0) {

                int listSize = 1;

                List<Map<String, Object>> sonSqlMapList = (List<Map<String, Object>>) sonModelSqlMap.get(ValueUtil.toStr(iteratorKey));

                for (Map<String, Object> sonSqlMap : sonSqlMapList) {
                    params.put("sql", sonSqlMap.get("sonQql"));

                    List<String> codeList = (List) sonSqlMap.get("codeList");
                    for (String code : codeList) {
                        Map<String, Object> keyMap = parseMapForFilter(map, code);
                        if (keyMap.size() > 0) {
                            params.put(code, map.get(keyMap.keySet().iterator().next()));
                        }

                    }
                    List<Map<String, Object>> sonMapList = mryeMapper.searchList(params);
                    if (sonMapList.size() > 0) {
                        //二级子集
                        if (sonMapList.size() > 0) {
                            map.put("list" + listSize + "|" + sonSqlMap.get("list"), sonMapList);
                            listSize++;
                        }

                        for (Map<String, Object> sonMap : sonMapList) {
                            if (sonMap.size() > 0) {
                                splicingData(sonMapList, sonModelSqlMap, iteratorKey - 1);
                            }
                        }

                    }
                }

            }

        }

    }

    /**
     * 添加字段属性存储
     *
     * @param fieldAttribute
     * @param customModelInfoForm
     */
    public void addFieldAttribute(Map<String, Object> fieldAttribute, CustomModelInfoForm customModelInfoForm) {
        //显示名称|显示别名|类型|位置|大小|颜色|排序|是否列表显示|是否头部显示|是否头部加粗|是否可编辑|控件大小|是否数据库字段|枚举|子模块|必填数据 Y/N|关联组件|关联key|默认值|数据来源 1默认，2枚举，3表里
        fieldAttribute.put(customModelInfoForm.getShowName() + "|" + customModelInfoForm.getTableFieldAlias() + "|" + customModelInfoForm.getShowPosition(), customModelInfoForm.getShowName() + "|" + customModelInfoForm.getTableFieldAlias() + "|" + customModelInfoForm.getControlType() + "|" + customModelInfoForm.getFontSize() + "|" + customModelInfoForm.getFontColor() + "|" + customModelInfoForm.getSort() + "|" + customModelInfoForm.getIsList() + "|" + customModelInfoForm.getIsHeadData() + "|" + customModelInfoForm.getIsHeadBold() + "|" + customModelInfoForm.getIsEditable() + "|" + customModelInfoForm.getControlSize() + "|" + customModelInfoForm.getIsDatabase() + "|" + customModelInfoForm.getEnumerationKey() + "|" + customModelInfoForm.getSonModel() + "|" + customModelInfoForm.getIsNeedData() + "|" + customModelInfoForm.getRelationAssembly() + "|" + customModelInfoForm.getRelationKey() + "|" + customModelInfoForm.getDefaultValue() + "|" + customModelInfoForm.getDataSource());


    }

    /**
     * 从map中查询想要的map项，根据key
     */
    public static Map<String, Object> parseMapForFilter(Map<String, Object> map, String filters) {
        if (map == null) {
            return null;
        } else {
            Map<String, Object> finalMap = map;
            map = map.entrySet().stream()
                    .filter((e) -> checkKey(finalMap, e.getKey(), filters))
                    .collect(Collectors.toMap(
                            (e) -> (String) e.getKey(),
                            (e) -> e.getValue()
                    ));
        }
        return map;

    }

    /**
     * 通过indexof匹配想要查询的字符
     */
    private static boolean checkKey(Map<String, Object> map, String key, String filters) {
        if (key.indexOf(filters) > -1 && key.indexOf("list") == -1) {
            if (map.get(key) == null) {
                return false;
            }
            return true;
        } else {
            return false;
        }
    }
}
